import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/update_book")
public class UpdateBook extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        String number = request.getParameter("number");
        String name = request.getParameter("name");
        String author = request.getParameter("author");

        String url = "jdbc:mysql://101.37.236.199:3306/linux_exam";
        String user = "root";
        String password = "1qaz@WSX#EDC";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection conn = DriverManager.getConnection(url, user, password)) {
                String sql = "UPDATE t_book SET name=?, author=? WHERE number=?";
                PreparedStatement stmt = conn.prepareStatement(sql);
                stmt.setString(1, name);
                stmt.setString(2, author);
                stmt.setString(3, number);
                int affectedRows = stmt.executeUpdate();
                if (affectedRows > 0) {
                    response.getWriter().write("updated");
                } else {
                    response.getWriter().write("not found");
                }
            }
        } catch (Exception e) {
            response.getWriter().write("error: " + e.getMessage());
        }
    }
}
